package com.mby.controller;

import com.mby.entity.*;
import com.mby.utils.ResultUtil;
import com.mby.utils.SecurityHelper;
import com.mby.utils.UserUtil;
import com.mby.utils.WebConstant;
import net.dongliu.requests.Header;
import net.dongliu.requests.Requests;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.http.util.TextUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;

/**
 * Created by noah on 2018/4/15.
 */
@RestController
public class UserController extends BaseController{

    /**
     * 获取经销商所有用户
     * get /live/users?dealer_id=BJB
     * @return
     * @throws Exception
     */
    @GetMapping(value = "/users")
    public void getUsers() throws Exception{
        respData(mongoTool.findMany("","{'dealerId':'"+currentUser().getDealerId()+"',}","", User.class));
    }

    @PostMapping(value = "/users")
    public void createUsers(@RequestBody User user) throws Exception{
        user.setLoginName(user.getLoginName().toLowerCase());
        if(user.getLoginName().substring(0,3).equals("MBY")){
            long count = mongoTool.count("{'loginName':'"+user.getLoginName()+"'}",User.class);
            if(count == 0){
                user.setDealerId(null);
                user.setPassword(SecurityHelper.generate(user.getPassword()));
                mongoTool.addOne(user);
                respData(user);
            }else{
                respData("LoginName Is Existent");
            }
        }else{
            respData("LoginName Must Start With MBY");
        }
    }

    @PutMapping(value = "/users")
    public void updateUsers(@RequestBody User user) throws Exception{
        mongoTool.update(user,"{'id':"+currentUser().getId()+"}", User.class);
        userUpdate(currentUser().getId().toString());
        respData(ok);
    }

    @PutMapping(value = "/users/avatar")
    public void updateUsersAvatar() throws Exception{
        mongoTool.findAndUpdate("{'avatarVer+':1}","{'id':"+currentUser().getId()+"}", User.class);
        userUpdate(currentUser().getId().toString());
        respData(ok);
    }

    @GetMapping(value = "/users/sync")
    public void syncUsers(String dealer_id) throws Exception{
        if(dealer_id != null && !"".equals(dealer_id)){
            syncDataByDealer(dealer_id);
        }else{
            List<?> list = mongoTool.findMany("","", Dealer.class);
            if(list != null){
                Dealer dealer;
                for(int i=0;i<list.size();i++){
                    dealer = (Dealer)list.get(i);
                    syncDataByDealer(dealer.getId());
                }
            }
        }
        respData(ok);
    }

    /**
     * 车主的push设备信息
     */
    @RequestMapping(value = "/users/device_tokens" ,method = RequestMethod.POST, produces = "application/json; charset=UTF-8")
    public void add(@RequestBody DeviceToken device_token){
        if(isNotNull(device_token.getDeviceToken())){
            long count = mongoTool.count("{'userId':"+currentUser().getId()+"}",DeviceToken.class);
            if(count > 0){
                mongoTool.findAndUpdate("{'deviceToken':'"+device_token.getDeviceToken()+"','createdAt':'"+getNow()+"','platform':'"+device_token.getPlatform()+"'}","{'userId':"+currentUser().getId()+"}",DeviceToken.class);
            }else{
                mongoTool.findAndUpdate("{'userId':"+currentUser().getId()+",'createdAt':'"+getNow()+"','platform':'"+device_token.getPlatform()+"'}","{'deviceToken':'"+device_token.getDeviceToken()+"'}",DeviceToken.class);
            }
            respData(ok);
        }else{
            respErr("DeviceToken Can Not Be null");
        }
    }

    private void syncDataByDealer(String dealer_id){
        mongoTool.delete("{'dealerId':'"+dealer_id+"'}",User.class);
        String result = Requests.get(WebConstant.DMS_USER_URL+"&dealerCode="+dealer_id)
                .headers(new Header("content-type","application/json;charset=UTF-8"))
                .verify(false)
                .send().readToText();
        result = "{'users':"+result+"}";
        JSONObject obj = JSONObject.fromObject(result);
        JSONArray users = obj.getJSONArray("users");
        if(users != null){
            Boolean quited;Boolean ok; String filtedRoleName,filtedRoleId;
            for(int i=0;i<users.size();i++) {
                ok = true;
                JSONObject user = users.getJSONObject(i);
                if (user.containsKey("USER_CODE")) {
                    if(user.getString("USER_CODE") != null && !"".equals(user.getString("USER_CODE")) && !"null".equals(user.getString("USER_CODE"))){
                        String IS_ONJOB = user.getString("IS_ONJOB");
                        if ("10081001".equals(IS_ONJOB)) {
                            quited = false;
                        } else {
                            quited = true;
                        }
                        String update_str = "{'loginName':'" + user.getString("USER_CODE").toLowerCase() + "','dealerId':'" + user.getString("DEALER_CODE") + "',";
                        if (user.containsKey("EMPLOYEE_NAME")) {
                            update_str = update_str + "'userName':'" + user.getString("EMPLOYEE_NAME") + "'" + ",";
                        }else{
                            ok = false;
                        }
                        if (user.containsKey("PHONE")) {
                            update_str = update_str + "'phone':'" + user.getString("PHONE") + "'" + ",";
                        }
                        if (user.containsKey("EMP_ROLE")) {
                            filtedRoleName = UserUtil.filterRoleNames(user.getString("EMP_ROLE"));
                            if(filtedRoleName != null && !"".equals(filtedRoleName)){
                                update_str = update_str + "'roleName':'" + filtedRoleName + "'" + ",'roleNameOrg':'" + user.getString("EMP_ROLE") + "'" + ",";
                            }else{
                                ok = false;
                            }
                        }else{
                            ok = false;
                        }
                        if (user.containsKey("EMP_ROLE_ID")) {
                            filtedRoleId = UserUtil.filterRoleIds(user.getString("EMP_ROLE_ID"));
                            if(filtedRoleId != null && !"".equals(filtedRoleId)){
                                update_str = update_str + "'roleIds':'" + filtedRoleId + "'" + ",'roleIdsOrg':'" + user.getString("EMP_ROLE_ID") + "'" + ",";
                            }else{
                                ok = false;
                            }
                        }else{
                            ok = false;
                        }
                        update_str = update_str + "'quited':" + quited + "}";
                        if(ok){
                            if(!TextUtils.containsBlanks(user.getString("USER_ID"))){
                                mongoTool.findAndUpdate(update_str, "{'_id':" + user.getString("USER_ID") + "}", User.class);
                            }
                        }else{
                            System.out.println("not ok:"+user.toString());
                        }
                    }
                }
            }
        }
    }
}
